Execution Order of Behaviors
Inside the scripting runtime, the execution order of Behaviour elements, plays a crucial role in determining when and how each script is executed in relation to other objects in the scene. By default, the execution order follows the hierarchical structure of the scene, meaning that Behaviors are executed in the order in which they appear in the scene hierarchy. This ensures a natural flow of logic where parent objects are processed before their children.
Default Execution Order
By default, all Behavior components are assigned an executionIndex
value of 0
.
This means that unless specified otherwise, all Behaviors will be executed at the same level of priority and in the order they appear in the hierarchy. The default behavior ensures consistency in scenarios where you have simple scenes with fixed objects that don't require dynamic reordering.
Customizing Execution Order
You can override the default execution order of Behaviors by setting a custom executionIndex
. This index controls the relative execution priority of each Behavior.
By specifying a value for the executionIndex
, you can orchestrate complex behavior sequences and ensure that certain actions occur before or after others, regardless of their position in the hierarchy. The lower the execution index, the earlier the script will be executed. Higher values will make the Behavior execute later in the sequence.
Use Cases for Custom Execution Order
The ability to customize the execution order is particularly useful in more complex scenes or dynamic scenarios, such as:
1. Orchestrating Complex Behaviors
If multiple objects need to interact in a specific sequence (e.g., an object that triggers another object’s behavior when clicked), you can use the executionIndex
to ensure that the triggering object executes first.
2. Maintaining Consistency in Dynamic Scenes
In dynamic scenes where objects may be added, removed, or reordered in the hierarchy at runtime, setting a custom executionIndex
ensures that behaviors are still executed in a predictable and consistent order, regardless of how the scene changes.
3. Coordinating Interactions Between Related Objects
If objects are tightly coupled and need to update in a particular sequence (e.g., a parent object triggers behavior in a child object), you can set custom execution indices to control this relationship.